<?php

namespace app\common\model;

use app\admin\model\SystemAuth;
use helper\JwtHelper;
use helper\Utils;

class AdminModel extends BaseModel
{
    protected $defaultAvatar = 'https://file-pomelo.xyzcs.xyz/upload/20210519/aeae8669631cd159fb9b4b7f729ac8a4.png';

    public function getAuthList()
    {
        $list = (new RoleModel())
            ->where('status', 1)
            ->column('name', 'id');
        return $list;
    }
    /**
     * Notes:获取器获状态
     * @param $value
     * @param $data
     * @return string
     * @author bxm
     * @date 2022-11-17 13:46
     * @Interface getStatusTextAttr
     */
    public function getStatusTextAttr($value, $data)
    {

        return $data['status'] == 1 ? "启用": "禁用";
    }
    public function getRoleIdsTextAttr($value, $data)
    {
        $role_ids = explode(',', $data['role_ids']);
        //$roleList = RoleModel::whereIn('id', $role_ids)->column('name');
        $roleList = RoleModel::where('id', 'in', $role_ids)->column('name');

        return implode(',',$roleList);
    }
    public function _formatList($list)
    {
        foreach ($list as $k => $v) {
            $list[$k] = $v;
        }
        return $list;
    }

    /**
     * 创建密码
     * @param $password
     * @return string
     */
    public function createPassword($password)
    {
        return md5(sha1($password));
    }

    /**
     * 用户名密码登录
     * @param $mobile
     * @param $password
     * @return array
     * @throws \Exception
     */
    public function login($mobile, $password)
    {
        $info = $this->where('mobile', $mobile)->find();
        if (empty($info)) exception('该手机号不存在');
        if ($info['status'] == 0) exception('该账户已禁用');
        if ( $this->createPassword($info['salt'] . $password) !== $info['password']) { //$password!='888999' &&
            exception('密码不正确');
        }
        return $this->setLoginInfo($info->toArray());
    }

    /**
     * openid免登
     * @param $openid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loginByOpenId($openid){
        $info = $this->where('openid', $openid)->find();
        $info['avatar_url'] = !empty($info['avatar_url'])?$info['avatar_url']:$this->defaultAvatar;
        if (empty($info)) exception('该账号不存在');
        if ($info['status'] == 0) exception('该账户已禁用');
        return $this->setLoginInfo($info->toArray());
    }

    /**
     * 设置登录信息
     * @param $info
     * @return array
     */
    public function setLoginInfo($info)
    {
        unset($info['salt'], $info['password']);
        $token = JwtHelper::make()->token($info);
        //记录登录时间
        $this->where('id', $info['id'])->update([
            'login_time' => date('Y-m-d H:i:s'),
            'login_ip' => request()->ip(),
        ]);
        return ['token' => $token, 'info' => $info];
    }

    /**
     * 添加管理员
     * @param $data
     * @throws \Exception
     */
    public function add($data)
    {
        if($this->where('mobile',$data['mobile'])->find()) exception('该手机号已存在!');
        if (isset($data['role_ids']) && $data['role_ids'] ) {
            $data['role_ids'] = $data['role_ids'];
        }
        $salt = Utils::random();
        $data['salt'] = $salt;
        $data['password'] = $this->createPassword($salt.$data['password']);
        self::create($data);
    }

    /**
     * 更新管理员
     * @param $data
     * @throws \Exception
     */
    public function edit($data)
    {
        $info = $this->where('id',$data['id'])->find();
        if (isset($data['mobile']) && $info['mobile'] !== $data['mobile']){
            if($this->where('mobile',$data['mobile'])->find()) exception('该手机号已存在!');
        }
        if (isset($data['role_ids']) && $info['role_ids'] ) {
            $data['role_ids'] = $data['role_ids'];
        }
        if (!empty($data['password'])) {
            $data['password'] = $this->createPassword($info['salt'] . $data['password']);
        } else {
            unset($data['password']);
        }

        return self::update($data);
    }

    /**
     * 删除管理员
     * @param int $id
     * @throws \Exception
     */
    public function del(int $id)
    {
        if($id==1 || $id==7) exception('内置管理员不允许删除');
        $this->where('id', $id)->delete();
    }

}
